package com.quwan.common.service.impl.tnps;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.quwan.common.enums.StatusEnum;
import com.quwan.common.form.PushForm;
import com.quwan.common.result.PushDTO;
import com.quwan.common.result.TNPSResult;
import com.quwan.common.service.push.MsgSender;
import com.quwan.config.yml.PushConfig;
import com.tencent.xinge.XingeApp;
import com.tencent.xinge.bean.*;
import com.tencent.xinge.bean.ios.Alert;
import com.tencent.xinge.bean.ios.Aps;
import com.tencent.xinge.push.app.PushAppRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
@Slf4j
public class IosTNPSMessage implements MsgSender {
    XingeApp xingeApp = null;
    @Override
    public PushDTO pushAll(PushForm pushForm, PushConfig pushConfig) {
        try {
            xingeApp = XingeApp.Builder.class.newInstance()
                    .appId(pushConfig.getXinge().getIosAccessKey())
                    .secretKey(pushConfig.getXinge().getIosSecretKey())
                    .domainUrl(pushConfig.getXinge().getDomainUrl())
                    .build();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return pushIosBase(pushForm.getTitle(),pushForm.getContent(), AudienceType.all,null, pushConfig, xingeApp);
    }

    @Override
    public PushDTO pushToken(PushForm pushForm, PushConfig pushConfig) {
        try {
            xingeApp = XingeApp.Builder.class.newInstance()
                    .appId(pushConfig.getXinge().getIosSecretKey())
                    .secretKey(pushConfig.getXinge().getAndroidSecretKey())
                    .domainUrl(pushConfig.getXinge().getDomainUrl())
                    .build();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ArrayList<String> tokenList = new ArrayList<>();
        tokenList.add(pushForm.getToken());
        return pushIosBase(pushForm.getTitle(),pushForm.getContent(), AudienceType.token,tokenList, pushConfig,xingeApp);
    }


    /**
     * ios基础推送
     * @param title 标题
     * @param content 内容
     * @param audienceType 推送目标
     * @param tokenList 推送设备
     * @return
     */
    private PushDTO pushIosBase(String title, String content, AudienceType audienceType, ArrayList<String> tokenList, PushConfig pushConfig, XingeApp iosXinGeApp) {
        // 消息体
        Message message = getIosMessage(title,content);
        JSONObject resultJson = iosXinGeApp.pushApp(queryPushAppRequest(message, Platform.ios,audienceType,tokenList, pushConfig));
        return queryResult(resultJson);
    }

    /**
     * 获取推送返回字符串
     * @param message 推送消息
     * @param platform 平台类型
     * @param audienceType 推送木补考
     * @param tokenList 推送token
     * @return
     */
    private String queryPushAppRequest(Message message, Platform platform, AudienceType audienceType, ArrayList<String> tokenList, PushConfig pushConfig){
        // 推送请求消息
        PushAppRequest pushAppRequest = new PushAppRequest();
        Environment env = String.valueOf(Environment.dev.getType()).equals(pushConfig.getXinge().getEnvironment()) ? Environment.dev : Environment.product;
        // 推送环境
        pushAppRequest.setEnvironment(env);
        // 消息体
        pushAppRequest.setMessage(message);
        // 推送平台
        pushAppRequest.setPlatform(platform);
        // 消息类型
        pushAppRequest.setMessage_type(MessageType.notify);
        // 推送目标
        pushAppRequest.setAudience_type(audienceType);
        if (!CollectionUtils.isEmpty(tokenList)){
            pushAppRequest.setToken_list(tokenList);
        }
        return pushAppRequest.toString();
    }

    private Message getIosMessage(String title, String content) {
        // ios 消息设置
        MessageIOS messageIOS = new MessageIOS();
        // apple特有的消息体字段
        Aps aps = new Aps();
        // 标题和内容
        Alert alert = new Alert();
//        alert.setTitle(title);
//        alert.setBody(content);
        aps.setAlert(alert);
//        aps.setCategory("INVITE_CATEGORY");
        messageIOS.setAps(aps);

        Message message = queryMessage(title,content);
        message.setIos(messageIOS);
        return message;
    }

    /**
     * 获取推送返回实体类
     * @param ret
     * @return
     */
    private PushDTO queryResult(JSONObject ret) {
        TNPSResult tnpsResult = JSON.parseObject(ret.toString(),TNPSResult.class);
        boolean flag = checkPush(ret);
        PushDTO pushDTO;
        if (flag){
            pushDTO = new PushDTO(tnpsResult.getPush_id(), StatusEnum.SUCEESS.getCode());
            return pushDTO;
        }
        pushDTO = new PushDTO(null, StatusEnum.FAIL.getCode());
        return pushDTO;
    }

    /**
     * 效验推送结果
     * @param resultJson json字符串
     * @return
     */
    private Boolean checkPush(JSONObject resultJson){
        Boolean result = false;
        int ret_code = 1;
        try {
            ret_code = resultJson.getInt("ret_code");
            log.info("PushResult result is:{}" , resultJson.toString());
            return ret_code == 0 ? true :false;
        } catch (JSONException e) {
            log.error("error:{}",e);
        } finally {
            log.info(resultJson.toString());
        }
        return result;
    }

    /**
     * 获取Message
     * @param title 标题
     * @param content 消息内容
     * @return
     */
    private Message queryMessage(String title,String content){
        Message message = new Message();
        message.setTitle(title);
        message.setContent(content);
        return message;
    }
}
